package com.zhouyu.service;

import com.spring.BeanPostProcessor;
import com.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author xuxin
 * @create 2024-10-13 15:25
 */
@Component
public class ZhouyuBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        System.out.println("初始化bean：" + beanName + "之前");
        if (beanName.equals("userService")) {
            ((UserServiceImpl) bean).setAge(101);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println("初始化bean：" + beanName + "之后");
        if (bean instanceof OrderService) {
            ((OrderService) bean).setName("order-zhouyu");
        }

        if (bean instanceof UserServiceImpl) {
            Object instance = Proxy.newProxyInstance(ZhouyuBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("执行代理方法");
                    return method.invoke(bean, args);
                }
            });
            return instance;
        }

        return bean;
    }
}
